#include "mainwindow.h"
#include "mainwindow_p.h"
#include <QDebug>
#include <QWindow>
#include <QDesktopWidget>
#include <QApplication>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QMessageBox>
#include <QTimer>

#include <QFileDialog>
#include <QSettings>
#include <QStatusBar>
#include <QToolBar>
#include <QApplication>
#include <QScreen>
#include <QTextEdit>
#include "mdichild.h"

#include "application.h"

#include "version.h"

SINGLETON_IMPLIMENT(MainWindow)

MainWindow::MainWindow(QWidget *parent)
    : MainWindow(* new MainWindowPrivate(), parent)
{

}

MainWindow::MainWindow(MainWindowPrivate &d, QWidget *parent)
    : QMainWindow(parent)
    , DPTR_INIT(&d)
{
    DPTR_INIT_PRIVATE(MainWindow);

    qDebug() << "MainWindow...";
    m_instance = this;

    d.mdiArea = new QMdiArea(this);
    d.mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    d.mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setCentralWidget(d.mdiArea);
    connect(d.mdiArea, &QMdiArea::subWindowActivated,
            this, &MainWindow::updateMenus);

    createActions();
    createStatusBar();
    updateMenus();

    readSettings();

    setWindowTitle(tr("Application"));
//    setUnifiedTitleAndToolBarOnMac(true);

    //

    qDebug() << "MainWindow...completed";

//    emit d.curveAct->triggered(true);

    // test
    QTimer::singleShot(600, this, [=](){
//        emit d.uartConfigAct->triggered(true);
//        emit d.uartAct->triggered(true);

         emit d.electronicScaleIntervalRateCurveAct->triggered(true);
         emit d.electronicScaleWeightCurveAct->triggered(true);

//        emit d.hplcTimeProgramAct->triggered(true);

//        emit d.hplcCommonAct->triggered(true);
//        emit d.hplcDebugInfoAct->triggered(true);

//        emit d.hplcPumpAct->triggered(true);
//        emit d.hplcPumpPanelAct->triggered(true);

//        emit d.hplcAutoSamplerAct->triggered(true);
//        emit d.hplcAutoSamplerDeviceAct->triggered(true);

//        emit d.testAct->triggered(true);
//        emit d.curveTestAct->triggered(true);
//        emit d.fftTestAct->triggered(true);
//        emit d.sigSlotTestAct->triggered(true);

//        emit d.updateAct->triggered(true);
//        emit d.serialPortUpdaterAct->triggered(true);
    });
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    DPTR_D(MainWindow);
    d.mdiArea->closeAllSubWindows();
    if (d.mdiArea->currentSubWindow()) {
        event->ignore();
    } else {
        writeSettings();
        event->accept();
    }
}

MainWindow::~MainWindow()
{
}

QMdiArea *MainWindow::getMdiArea()
{
    DPTR_D(MainWindow);
    return d.mdiArea;
}

QMdiSubWindow *MainWindow::addSubWindow(QWidget *w)
{
    DPTR_D(MainWindow);
    return d.mdiArea->addSubWindow(w);
}

void MainWindow::enter(void)
{
    //update ctrls


}

void MainWindow::leave(void)
{

}




void MainWindow::newFile()
{
    MdiChild *child = createMdiChild();
    child->newFile();
    child->show();
}

void MainWindow::open()
{
    const QString fileName = QFileDialog::getOpenFileName(this);
    if (!fileName.isEmpty())
        openFile(fileName);
}

bool MainWindow::openFile(const QString &fileName)
{
    DPTR_D(MainWindow);
    if (QMdiSubWindow *existing = findMdiChild(fileName)) {
        d.mdiArea->setActiveSubWindow(existing);
        return true;
    }
    const bool succeeded = loadFile(fileName);
    if (succeeded)
        statusBar()->showMessage(tr("File loaded"), 2000);
    return succeeded;
}

bool MainWindow::loadFile(const QString &fileName)
{
    MdiChild *child = createMdiChild();
    const bool succeeded = child->loadFile(fileName);
    if (succeeded)
        child->show();
    else
        child->close();
    MainWindow::prependToRecentFiles(fileName);
    return succeeded;
}

static inline QString recentFilesKey() { return QStringLiteral("recentFileList"); }
static inline QString fileKey() { return QStringLiteral("file"); }

static QStringList readRecentFiles(QSettings &settings)
{
    QStringList result;
    const int count = settings.beginReadArray(recentFilesKey());
    for (int i = 0; i < count; ++i) {
        settings.setArrayIndex(i);
        result.append(settings.value(fileKey()).toString());
    }
    settings.endArray();
    return result;
}

static void writeRecentFiles(const QStringList &files, QSettings &settings)
{
    const int count = files.size();
    settings.beginWriteArray(recentFilesKey());
    for (int i = 0; i < count; ++i) {
        settings.setArrayIndex(i);
        settings.setValue(fileKey(), files.at(i));
    }
    settings.endArray();
}

bool MainWindow::hasRecentFiles()
{
    QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
    const int count = settings.beginReadArray(recentFilesKey());
    settings.endArray();
    return count > 0;
}

void MainWindow::prependToRecentFiles(const QString &fileName)
{
    QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());

    const QStringList oldRecentFiles = readRecentFiles(settings);
    QStringList recentFiles = oldRecentFiles;
    recentFiles.removeAll(fileName);
    recentFiles.prepend(fileName);
    if (oldRecentFiles != recentFiles)
        writeRecentFiles(recentFiles, settings);

    setRecentFilesVisible(!recentFiles.isEmpty());
}

void MainWindow::setRecentFilesVisible(bool visible)
{
    DPTR_D(MainWindow);
    d.recentFileSubMenuAct->setVisible(visible);
    d.recentFileSeparator->setVisible(visible);
}

void MainWindow::updateRecentFileActions()
{
    DPTR_D(MainWindow);
    QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());

    const QStringList recentFiles = readRecentFiles(settings);
    const int count = qMin(int(d.MaxRecentFiles), recentFiles.size());
    int i = 0;
    for ( ; i < count; ++i) {
        const QString fileName = QFileInfo(recentFiles.at(i)).fileName();
        d.recentFileActs[i]->setText(tr("&%1 %2").arg(i + 1).arg(fileName));
        d.recentFileActs[i]->setData(recentFiles.at(i));
        d.recentFileActs[i]->setVisible(true);
    }
    for ( ; i < d.MaxRecentFiles; ++i)
        d.recentFileActs[i]->setVisible(false);
}

void MainWindow::openRecentFile()
{
    if (const QAction *action = qobject_cast<const QAction *>(sender()))
        openFile(action->data().toString());
}

void MainWindow::save()
{
    if (activeMdiChild() && activeMdiChild()->save())
        statusBar()->showMessage(tr("File saved"), 2000);
}

void MainWindow::saveAs()
{
    MdiChild *child = activeMdiChild();
    if (child && child->saveAs()) {
        statusBar()->showMessage(tr("File saved"), 2000);
        MainWindow::prependToRecentFiles(child->currentFile());
    }
}

#ifndef QT_NO_CLIPBOARD
void MainWindow::cut()
{
    if (activeMdiChild())
        activeMdiChild()->cut();
}

void MainWindow::copy()
{
    if (activeMdiChild())
        activeMdiChild()->copy();
}

void MainWindow::paste()
{
    if (activeMdiChild())
        activeMdiChild()->paste();
}
#endif

void MainWindow::about()
{
   QMessageBox::about(this, tr("About application"),
            tr("<b>Version</b> %1").arg(APP_VERSION));
}

void MainWindow::updateMenus()
{
    DPTR_D(MainWindow);
    bool hasMdiChild = (activeMdiChild() != nullptr);
    d.saveAct->setEnabled(hasMdiChild);
    d.saveAsAct->setEnabled(hasMdiChild);
#ifndef QT_NO_CLIPBOARD
    d.pasteAct->setEnabled(hasMdiChild);
#endif
    d.closeAct->setEnabled(hasMdiChild);
    d.closeAllAct->setEnabled(hasMdiChild);
    d.tileAct->setEnabled(hasMdiChild);
    d.cascadeAct->setEnabled(hasMdiChild);
    d.nextAct->setEnabled(hasMdiChild);
    d.previousAct->setEnabled(hasMdiChild);
    d.windowMenuSeparatorAct->setVisible(hasMdiChild);

#ifndef QT_NO_CLIPBOARD
    bool hasSelection = (activeMdiChild() &&
                         activeMdiChild()->textCursor().hasSelection());
    d.cutAct->setEnabled(hasSelection);
    d.copyAct->setEnabled(hasSelection);
#endif
}

void MainWindow::updateWindowMenu()
{
    DPTR_D(MainWindow);
    d.windowMenu->clear();
    d.windowMenu->addAction(d.closeAct);
    d.windowMenu->addAction(d.closeAllAct);
    d.windowMenu->addSeparator();
    d.windowMenu->addAction(d.tileAct);
    d.windowMenu->addAction(d.cascadeAct);
    d.windowMenu->addSeparator();
    d.windowMenu->addAction(d.nextAct);
    d.windowMenu->addAction(d.previousAct);
    d.windowMenu->addAction(d.windowMenuSeparatorAct);

    QList<QMdiSubWindow *> windows = d.mdiArea->subWindowList();
    d.windowMenuSeparatorAct->setVisible(!windows.isEmpty());

    for (int i = 0; i < windows.size(); ++i) {
        QMdiSubWindow *mdiSubWindow = windows.at(i);
        MdiChild *child = qobject_cast<MdiChild *>(mdiSubWindow->widget());

        QString text;
        if (i < 9) {
            text = tr("&%1 %2").arg(i + 1)
                               .arg(child->userFriendlyCurrentFile());
        } else {
            text = tr("%1 %2").arg(i + 1)
                              .arg(child->userFriendlyCurrentFile());
        }
        QAction *action = d.windowMenu->addAction(text, mdiSubWindow, [this, mdiSubWindow]() {
            DPTR_D(MainWindow);
            d.mdiArea->setActiveSubWindow(mdiSubWindow);
        });
        action->setCheckable(true);
        action ->setChecked(child == activeMdiChild());
    }
}

MdiChild *MainWindow::createMdiChild()
{
    DPTR_D(MainWindow);
    MdiChild *child = new MdiChild;
    d.mdiArea->addSubWindow(child);

#ifndef QT_NO_CLIPBOARD
    connect(child, &QTextEdit::copyAvailable, d.cutAct, &QAction::setEnabled);
    connect(child, &QTextEdit::copyAvailable, d.copyAct, &QAction::setEnabled);
#endif

    return child;
}

void MainWindow::createActions()
{
    DPTR_D(MainWindow);

    d.createFileMenuActions_helper();

    d.createEditMenuActions_helper();

    d.createConnectionMenuActions_helper();

    d.createToolMenuActions_helper();

    d.createWindowMenuActions_helper();
    updateWindowMenu();

    menuBar()->addSeparator();

    d.createHelpMenuActions_helper();
}

void MainWindow::createStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}

void MainWindow::readSettings()
{
    QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
    qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName();
    const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
    if (geometry.isEmpty()) {
        const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
        resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
        move((availableGeometry.width() - width()) / 2,
             (availableGeometry.height() - height()) / 2);
    } else {
        restoreGeometry(geometry);
    }
}

void MainWindow::writeSettings()
{
    QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
    settings.setValue("geometry", saveGeometry());
}

MdiChild *MainWindow::activeMdiChild() const
{
    const DPTR_D(MainWindow);
    if (QMdiSubWindow *activeSubWindow = d.mdiArea->activeSubWindow())
        return qobject_cast<MdiChild *>(activeSubWindow->widget());
    return nullptr;
}

QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName) const
{
    const DPTR_D(MainWindow);
    QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();

    const QList<QMdiSubWindow *> subWindows = d.mdiArea->subWindowList();
    for (QMdiSubWindow *window : subWindows) {
        MdiChild *mdiChild = qobject_cast<MdiChild *>(window->widget());
        if (mdiChild->currentFile() == canonicalFilePath)
            return window;
    }
    return nullptr;
}

void MainWindow::switchLayoutDirection()
{
    if (layoutDirection() == Qt::LeftToRight)
        QGuiApplication::setLayoutDirection(Qt::RightToLeft);
    else
        QGuiApplication::setLayoutDirection(Qt::LeftToRight);
}
